package com.lawyers.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lawyers.common.UserVO;
import com.lawyers.database.DBAcciones;
import com.lawyers.form.UsuarioForm;
import com.lawyers.util.MD5;

public class UsuarioAction extends Action{
	
	private static Logger logger = Logger.getLogger(LoginAction.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{
		logger.info("Hi");
		String forward = "display";

		UsuarioForm userForm = (UsuarioForm) form;
		String accion = userForm.getAccion();
		UserVO userVO = (UserVO) request.getSession().getAttribute("USUARIO");

		if (userVO == null || !userVO.getPerfil().equalsIgnoreCase("a"))
			return mapping.findForward("login");
		
		userForm.setListaUsuarios(DBAcciones.getUsuarios());
		
		if("aceptar".equalsIgnoreCase(accion)){
			
			UserVO user = new UserVO();
			user.setIdUsuario(userForm.getIdUsuario());
			user.setPassword(MD5.parse(userForm.getPassword()));
			user.setPerfil(userForm.getPerfil());
			user.setUsername(userForm.getUsername());
			
			if(DBAcciones.insertarUsuario(user)){
				forward = "aceptar";
				userForm.setIdUsuario("");
				userForm.setPassword("");
				userForm.setPerfil("");
				userForm.setUsername("");
			}
			else{
				forward = "error";
				userForm.setIdUsuario("");
				userForm.setPassword("");
				userForm.setPerfil("");
				userForm.setUsername("");
			}
				
			
		}else if("eliminar".equalsIgnoreCase(accion)){
			if(DBAcciones.eliminarUsuario(userForm.getIdUsuario())){
				forward = "aceptar";
				userForm.setIdUsuario("");
				userForm.setPassword("");
				userForm.setPerfil("");
				userForm.setUsername("");
			}
			else{
				forward = "error";
				userForm.setIdUsuario("");
				userForm.setPassword("");
				userForm.setPerfil("");
				userForm.setUsername("");
			}
		}else if("habilitar".equalsIgnoreCase(accion)){
			if(DBAcciones.habilitarUsuario(userForm.getIdUsuario())){
				forward = "aceptar";
				userForm.setIdUsuario("");
				userForm.setPassword("");
				userForm.setPerfil("");
				userForm.setUsername("");
			}
			else{
				forward = "error";
				userForm.setIdUsuario("");
				userForm.setPassword("");
				userForm.setPerfil("");
				userForm.setUsername("");
			}
		}else{
			userForm.setIdUsuario("");
			userForm.setPassword("");
			userForm.setPerfil("");
			userForm.setUsername("");
		}
			
			
		
		return mapping.findForward(forward);
	}

}
